package com.handinfo.engine.net;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import com.handinfo.engine.GameMIDlet;
import com.handinfo.engine.GameManager;
import com.handinfo.game.UserScreen;
import com.handinfo.util.Tools;


/**
 * HTTPConnect
 * @author 赵铮
 * */
public class HttpConnect implements Runnable
{
	public String SERVER1 = "test/getHeader.jsp";
	public String SERVER2 = "rdp/v5.1/serviceinfo.aspx?ua=Dopod830&ServiceID=85&flat=6&version=2.11";
	public String HOST1 = "wap.monternet.com";
	public static String HOST2 = "58.215.185.99";//"211.151.33.73";//"58.215.185.99";//218.200.160.29
	public static int SERVER_PORT = 23591;//18008;//23590;
	public String CM_WAP = "http://10.0.0.172/";
	public String SERVER;
	public String HOST;
	public String m_number = null;//每次登陆获取的手机号
	public String body;//取得的字符串
	public String[] url;//取得的连接区 0:IP和1:端口号
	public static String NUMBER = "";//获得的手机号
	public static String USERAGNET = "0";//手机型号
	public static String IMEI = "0";
	public byte state = 0;//处理状态
	public byte s_success;//0连接中 1 成功 2失败
	public final byte CM_GETTELNUMBER = 0;//获取手机号
	public final byte CM_GETSERVERLIST = 1;//获取服务器列表
	public byte m_type = 0;//取手机号的参数
	public byte m_optype = 1;//操作读取的类型 0返回一行 不含空格 1返回一行含空格  其他 返回所有 不含空格和换行
	public boolean isWap;//是否用WAP连接方式

	/**
	 * @param _isWap 是否用WAP连接
	 * */
	public HttpConnect(boolean _isWap)
	{
		isWap = _isWap;
	}

	/**
	 * @param SERVER
	 * @Param HOST
	 * @param _isWap 是否用WAP连接
	 * */
	public HttpConnect(String server, String host, boolean _isWap)
	{
		SERVER = server;
		HOST = host;
		isWap = _isWap;
	}

	/**
	 * 设置连接状态
	 * @param index
	 * */
	public void SetState(byte index)
	{
		state = index;
	}

//	/**
//	* 判断该手机号码是否是移动手机号段
//	* @param phone
//	* @return true or false
//	* @throws Exception
//	*/
//	private boolean isMobileNumber(String phone) throws ServiceException
//	{
//		boolean isExist = false;
//		//phone = phone.trim();//移除空白字符
//		if (phone == null || phone.length() < 7) {
//			try {
//				throw new Exception("wrong phone length");
//			}
//			catch (Exception ex) {
//				ex.printStackTrace();
//			}
//		}
//		String code = "";
//		if( phone.startsWith("86")){
//			code = phone.substring(2,7);
//		}else{
//		    code = phone.substring(0, 7);//取前7位有效判断即可
//		}
//		if (code.startsWith("134") || code.startsWith("135")
//				|| code.startsWith("136") || code.startsWith("137")
//				|| code.startsWith("138") || code.startsWith("139")
//				|| code.startsWith("159") || code.startsWith("158")
//				|| code.startsWith("150") || code.startsWith("157")
//				|| code.startsWith("151") || code.startsWith("188")
//				|| code.startsWith("189")) {
//			isExist = true;
//		}
//		return isExist;
//
//	}

//	public static String getMobileType(String mobile)
//	{
//		if (mobile.startsWith("0") || mobile.startsWith("+860")) {
//			mobile = mobile.substring(mobile.indexOf("0") + 1, mobile.length());
//		}
//		ArrayList chinaUnicom = new ArrayList();
//		ArrayList chinaMobile1 = new ArrayList();
//		ArrayList chinaMobile2 = new ArrayList();
//		chinaUnicom.addElement(new String[] { "130", "131", "132", "133" });
//		chinaMobile1.addElement(new String[] { "135", "136", "137", "138", "139", "158", "159" });
//		chinaMobile2.addElement(new String[] { "1340", "1341", "1342", "1343", "1344", "1345", "1346", "1347", "1348" });
//		boolean bolChinaUnicom = (chinaUnicom.contain(mobile.substring(0, 3)));
//		boolean bolChinaMobile1 = (chinaMobile1.contain(mobile.substring(0, 3)));
//		boolean bolChinaMobile2 = (chinaMobile2.contain(mobile.substring(0, 4)));
//		chinaUnicom.removeAllElements();
//		chinaMobile1.removeAllElements();
//		chinaMobile2.removeAllElements();
//		chinaUnicom = null;
//		chinaMobile1 = null;
//		chinaMobile2 = null;
//		if (bolChinaUnicom) {
//			return "1";//联通
//		}
//		else if (bolChinaMobile1 || bolChinaMobile2) {
//			return "2"; //移动
//		}
//		else {
//			return "3"; //其他为电信
//		}
//	}
	/**
	 * 获取电话号码
	 * @param String 提取的字符串
	 * @param int 0为梦网测试1为音乐随身听
	 * */
	public String getNumber(String str, byte type)
	{
		if (str == null)
			return null;
		String temp = null;
		int index = 0;
		if (type == 0) {
			temp = "x-up-calling-line-id=";
			index = str.indexOf(temp);
			if (index == -1) {
				temp = "X-Up-Calling-Line-ID=";
				index = str.indexOf(temp);
			}
		}
		else {
			temp = "<mdn>";
			index = str.indexOf(temp);
		}
		if (index == -1) {
			return null;
		}
		temp = str.substring((index + temp.length()));
		StringBuffer buff = new StringBuffer();
		index = temp.length();
		for (int i = 0; i < index; i++) {
			char c = temp.charAt(i);
			if (c >= 48 && c <= 57) {
				buff.append(c);
			}
			else {
				break;
			}
		}
		temp = buff.toString();
		buff = null;
		return temp.trim();
	}

	/**
	 * 获取电话号码
	 * @param String 提取的字符串
	 * @param int 0为梦网测试1为音乐随身听
	 * */
	public String getUserAgent(String str, byte type)
	{
		if (str == null)
			return null;
		String str1 = null;
		String str2 = null;
		int index = 0;
		int endindex = 0;
		if (type == 0) {
			str1 = "User-Agent=";
			index = str.indexOf(str1);
			str2 = "UNTRUSTED";
			endindex = str.indexOf(str2);
		}
		else {
			str1 = "User-Agent:";
			index = str.indexOf(str1);
		}
		Tools.debugPrintln("index=" + index);
		if (index == -1) {
			return null;
		}
		Tools.debugPrintln("endindex=" + endindex);
		str2 = null;
		str2 = str.substring((index + str1.length()), endindex);
		return str2.trim();
	}

/**
	public void SocketConnect(byte type,byte optype) throws IOException
	{
		StreamConnection conn = null;
		OutputStream os = null;
		InputStream is = null;
		try {
			conn = (StreamConnection)Connector.open("socket://106.3.241.131:1928");
			// 发送和回复的请求
			os = conn.openDataOutputStream();
			is = conn.openDataInputStream();

			// 在此我们使用HTTP 1.0，HTTP 1.1自己还需要处理chunk，比较麻烦
			StringBuffer buff = new StringBuffer();
			buff.append("GET /test/getHeader.jsp HTTP/1.0\r\n");
			buff.append("Host:wap.monternet.com:80\r\n");
			buff.append("Accept-Language: zh-cn\r\n");
			buff.append("Connection: Keep-Alive\r\n");
            buff.append("\r\n");
			os.write(buff.toString().getBytes());
			buff = null;
			os.flush();

			InputStreamReader reader = new InputStreamReader(is,"UTF-8");
			String temp;
			boolean flag = false;
    		while (!flag) {
				temp = readLine(reader, optype);
				Tools.debugPrintln("reader:" + temp);
				if (temp == null) {
					flag = true;
				}
				else {
					body = null;
					switch (type) {
						case 0://获取手机号
						case 1:
							body = getNumber(temp, type);
							if (body != null) {
								m_number = body;
							}
							if ( USERAGNET == null || USERAGNET.length() < 2) {
								body = null;
								body = getUserAgent(temp, type);
								if ( body != null ) {
									USERAGNET = body;
								}
							}
							if ( m_number != null && USERAGNET != null && USERAGNET.length() > 2) {
								flag = true;
							}
							break;
						default://获取服务器列表
							body = temp;
							flag = true;
							break;
					}
				}
			}
			reader.close();
			reader = null;
		}
		catch (Exception ex) {
			Tools.debugPrintln("HTTP SOCKET 异常了"+ex.toString());
		}
		finally {
			if (is != null) {
				try {
					is.close();
				}
				catch (IOException ex) {
					ex.printStackTrace();
				}
			}

			if (os != null) {
				try {
					os.close();
				}
				catch (IOException ex) {
					ex.printStackTrace();
				}
			}

			if (conn != null) {
				try {
					conn.close();
				}
				catch (IOException ex) {
					ex.printStackTrace();
				}
			}
		}

	}
*/
	/**
	 * 连接CMWAP
	 * @param type 0梦网测试1音乐随身听-1请求服务器列表
	 * */
	public void Connect(byte type, byte optype)
	{

		HttpConnection conn = null;
		InputStream is = null;
		try {

			String url = "";
			String host = "";

			switch (state) {
				case CM_GETTELNUMBER:
					if (isWap) {
						if (m_type == 0) {
							url = CM_WAP + SERVER1;
							host = HOST1;
						}
						else {
							url = CM_WAP + SERVER2;
							host = HOST2;
						}
					}
					else {
						if (m_type == 0) {
							url = HOST1 + SERVER1;
						}
						else {
							url = HOST2 + SERVER2;
						}
					}
					break;
				case CM_GETSERVERLIST:
					if (isWap) {
						url = CM_WAP + SERVER;
						host = HOST;
					}
					else {
						url = "http://"+HOST +"/"+ SERVER;
					}
					break;
				default:
					break;
			}
     	    Tools.debugPrintln("url="+url);
            conn = (HttpConnection) Connector.open(url, Connector.READ, true);
			if (isWap) {
				conn.setRequestProperty("x-online-host", host);

				//conn.setRequestProperty("User-Agent", "Nokia6670/2.0 (4.0445.0ch)");
			}

			conn.setRequestMethod(HttpConnection.GET);

			int code = conn.getResponseCode();

			//int length = (int)conn.getLength();
			//codeString[codeindex] = "state:"+code+";length:"+length;
			//Tools.debugPrintln("codeString["+codeindex+"]="+codeString[codeindex]);

			if (code != HttpConnection.HTTP_OK) {
				throw new Exception();
			}

			is = conn.openDataInputStream();
			if (is == null) {
				throw new Exception();
			}

			InputStreamReader reader = new InputStreamReader(is, "UTF-8");
			String temp;
			boolean flag = false;
			while (!flag) {
				temp = readLine(reader, optype);
				Tools.debugPrintln("reader:" + temp);
				if (temp == null) {
					flag = true;
				}
				else {
					body = null;
					switch (type) {
						case 0://获取手机号
						case 1:
							body = getNumber(temp, type);
							if (body != null) {
								m_number = body;
							}
							if ( USERAGNET == null || USERAGNET.length() < 2) {
								body = null;
								body = getUserAgent(temp, type);
								if ( body != null ) {
									USERAGNET = body;
								}
							}
							if ( m_number != null && USERAGNET != null && USERAGNET.length() > 2) {
								flag = true;
							}
							break;
						default://获取服务器列表
							body = temp;
							Tools.debugPrintln("body="+body);
							flag = true;
							break;
					}
				}
			}
			reader.close();
			reader = null;

			/**
			 * 一般取返回流内容
			 * byte[] buf = new byte[is.available()];
			 * while (true) {
			 * int availSize = is.read(buf, 0, buf.length);
			 * if (availSize == -1) {
			 * break;
			 * }
			 * body = new String(buf, 0, availSize);
			 * }
			 * buf = null;
			 * if( body != null ){
			 * byte[] b = body.getBytes();
			 * body = new String(b, "UTF-8");
			 * }
			 */
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
		finally {
			if (is != null) {
				try {
					is.close();
				}
				catch (IOException ex) {
					ex.printStackTrace();
				}
			}
			if (conn != null) {
				try {
					conn.close();
				}
				catch (IOException ex) {
					ex.printStackTrace();
				}
			}
		}
	}

	/** 存获取的电话号码 */
	private void savePhone()
	{
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			DataOutputStream dos = new DataOutputStream(baos);
			dos.writeUTF(NUMBER);
			dos.writeUTF(USERAGNET);
			dos.writeUTF(IMEI);
			Tools.saveRecord(baos.toByteArray(), "phone", 1);
			dos.close();
			baos.close();
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 载入电话号
	 *
	 * @param id
	 * @throws Exception
	 */
	private final void loadPhone()
	{
		byte[] data = Tools.loadRecord("phone", 1);
		try {
			if (data == null) {
				throw new Exception();
			}
			else {
				ByteArrayInputStream bais = new ByteArrayInputStream(data);
				DataInputStream dis = new DataInputStream(bais);
				NUMBER = dis.readUTF();
				USERAGNET = dis.readUTF();
				IMEI = dis.readUTF();
				bais.close();
				dis.close();
				bais = null;
				dis = null;
			}
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/** 存获取的IP地址 */
	public static void saveAddress(String url,int index)
	{
//		try {
//			ByteArrayOutputStream baos = new ByteArrayOutputStream();
//			DataOutputStream dos = new DataOutputStream(baos);
//			dos.writeUTF(url);
//			dos.writeInt(index);;
//			Tools.saveRecord(baos.toByteArray(), GameMIDlet.m_iprecord, 1);
//			dos.close();
//			baos.close();
//		}
//		catch (Exception ex) {
//			ex.printStackTrace();
//		}
	}


    private String getUA(){
    	String ua = null;
    	if( null == ua ){
			//NOKIA
			ua = System.getProperty("microedition.platform");
    	}
        if( null == ua ){
			//SE
			ua = System.getProperty("microedition.platform ");
        }
    	if( ua == null ){
    		return ua = "0";
    	}
    	return ua.trim();
    }

	private String getIMEI()
	{
		String imei = null;
		if( null == imei ){
			//NOKIA
			imei = System.getProperty("com.nokia.mid.imei");
		}
		if( null == imei ){
			//SE
			imei = System.getProperty("com.sonyericsson.imei");
		}
		if( null == imei ){
			//SAMSUNG
			imei = System.getProperty("com.samsung.imei");
		}
		if( null == imei ){
			//MOTO
			imei = System.getProperty("IMEI");
			if (imei == null) {
				imei = System.getProperty("phone.imei");
			}
		}
		if( null == imei ){
			//SIEMENS
			imei = System.getProperty("com.siemens.IMEI");
		}
		if( imei == null ){
			return "0";
		}else{
			StringBuffer buff = new StringBuffer();
			for(int i=0;i<imei.length();i++){
				char c = imei.charAt(i);
				if (c >= 48 && c <= 57) {
					buff.append(c);
				}
			}
			imei = buff.toString();
			buff = null;
		}
		return imei.trim();
	}

	public void run()
	{
		switch (state) {
			case CM_GETTELNUMBER://获取号码
				initRMS();
				m_type = 0;
				Tools.debugPrintln("HTTP请求第1次");
				Connect(m_type, m_optype);
				if ( m_number == null || m_number.length() < 11) {
					Tools.debugPrintln("HTTP请求第2次");
					Connect(m_type, m_optype);
				}
				if (m_number == null ||  m_number.length() < 11) {
					m_type = 1;
					Tools.debugPrintln("HTTP请求第3次");
					Connect(m_type, m_optype);
				}
				if ( m_number == null || m_number.length() < 11 ) {
					 s_success = 2;
				}else {
					 s_success = 1;
					 NUMBER = m_number;
				}
				savePhone();
				if (s_success == 1) {
					Tools.debugPrintln("手机号码获取成功: " + NUMBER + ":UA=" + USERAGNET + ";IMEI=" + IMEI);
					dipose();
				}
				else if (s_success == 2) {
					Tools.debugPrintln("手机号码获取失败！ ");
					dipose();
				}
				UserScreen.m_httpsuccess = s_success;
				break;
			case CM_GETSERVERLIST://获取列表信息
				Tools.debugPrintln("准备HTTP请求获取信息");
				m_type = -1;
				m_optype = -1;
				Connect(m_type, m_optype);
				if (body != null) {
					url = Tools.splitString(body, ',');
					if (url != null
							&& url.length == 3
							&& Integer.parseInt(url[0]) == 10000) {
						s_success = 1;
					}
					else {
						s_success = 2;
					}
				}
				else {
					s_success = 2;
				}
//				if (s_success == 1) {
//					Tools.debugPrintln("IP获取成功: " + url[1].concat(url[2]));
//					GameManager.SERVER_URL = url[1];
//					GameManager.SERVER_PORT = Integer.parseInt( url[2].trim());
//					dipose();
//				}
//				else if (s_success == 2) {
//					Tools.debugPrintln("IP获取失败！ ");
//					dipose();
////					GameManager.SERVER_URL = "211.151.33.73";
////					GameManager.SERVER_PORT = 7878;
//					GameManager.SERVER_URL = HttpConnect.HOST2;//"211.151.33.73";//211.151.33.73
//					GameManager.SERVER_PORT = HttpConnect.SERVER_PORT;
//
//				}
				//重要
//				GameManager.SERVER_URL = "211.151.33.72";
//				GameManager.SERVER_PORT = 23591;
//				GameManager.SERVER_URL = HttpConnect.HOST2;//"211.151.33.73";//211.151.33.73
//				GameManager.SERVER_PORT = HttpConnect.SERVER_PORT;
//				saveAddress(GameManager.SERVER_URL, GameManager.SERVER_PORT);
				break;
			default:
				break;
		}
	}

	/**
	 * @param InputStreamReader
	 * @param byte
	 * -1:返回所有 0：返回一行 不含空格 1返回一行 含空格
	 */
	private String readLine(InputStreamReader reader, byte optype)
	{
		StringBuffer line = new StringBuffer();
		String temp;
		try {
			if (reader == null) {
				return null;
			}
			int c = -1;
			boolean bytesRead = false;
			while ((c = reader.read()) != -1) {
				bytesRead = true;
				char ch = (char) c;
				switch (optype) {
					case 0:
						if (ch == '\n') {
							break;
						}
						if (ch != '\r') {
							line.append(ch);
						}
						break;
					case 1:
						if (ch == '\n') {
							break;
						}
						line.append(ch);
						break;
					default:
						if (ch != '\r' && ch != '\n') {
							line.append(ch);
						}
						break;
				}
			}
			if (!bytesRead) {
				return null;
			}
			temp = line.toString();
			line = null;
			return temp;
		}
		catch (EOFException eof) {
			return line.length() > 0 ? line.toString() : null;
		}
		catch (IOException ex) {
			ex.printStackTrace();
			return null;
		}
	}

	public void initRMS(){
		if( Tools.haveRecord("phone")){
			loadPhone();
			if( IMEI == null || IMEI.length() < 2){//IMEI 为空
				IMEI = getIMEI();
			}
			if( USERAGNET != null && USERAGNET.length() > 2){//有UA按行取
				m_optype = 0;
			}
		}else{
			USERAGNET = getUA();
			IMEI = getIMEI();
		}
	}


	public void dipose()
	{
		SERVER1 = null;
		SERVER2 = null;
		HOST1 = null;
		HOST2 = null;
		CM_WAP = null;
	}
}
